package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 招生战队 前端控制器
 * </p>
 *
 * @author min
 * @since 2023-02-10
 */
@RestController
@RequestMapping("/api/enrollTeam")
@Scope("prototype")
public class EnrollTeamController extends BaseController {

    @Autowired
    IEnrollTeamService iEnrollTeamService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    IEnrollTeamMemberService iEnrollTeamMemberService;

    @GetMapping()
    public Result findAll(@RequestParam Map reMap) {
        try {

            String status = reMap.get("status") != null ? (String) reMap.get("status") : "";
            String name = reMap.get("name") != null ? (String) reMap.get("name") : "";
            String yearPart = reMap.get("yearPart") != null ? (String) reMap.get("yearPart") : "";
            String quarterNum = reMap.get("quarterNum") != null ? (String) reMap.get("quarterNum") : "";

            List<EnrollTeam> enrollTeamList = iEnrollTeamService.getTreeList(0L, yearPart, quarterNum, status);
            for (EnrollTeam et : enrollTeamList) {
                et.setChildNode(iEnrollTeamService.getTreeList(et.getId(), yearPart, quarterNum, status));
            }

            return new Result(Code.OK, new PageResult(enrollTeamList, (long) enrollTeamList.size(), 1L));

        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }


    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") String id) {
        try {
            EnrollTeam enrollTeam = iEnrollTeamService.getById(id);
            return new Result(Code.OK, enrollTeam);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }


    @PostMapping()
    public Result save(@RequestBody EnrollTeam enrollTeam) {
        try {
            Organization organization = iOrganizationService.getById(enrollTeam.getSchoolId());
            if (organization != null) {
                enrollTeam.setSchoolName(organization.getName());
            }
            if (enrollTeam.getPid() != null && !enrollTeam.getPid().equals(0)) {
                EnrollTeam enrollTeamParent = iEnrollTeamService.getById(enrollTeam.getPid());
                if (enrollTeamParent == null) {
                    return new Result(Code.ERROR, "", "父级战队不存在");
                }
                enrollTeam.setSchoolId(enrollTeamParent.getSchoolId());
                enrollTeam.setSchoolName(enrollTeamParent.getSchoolName());
                enrollTeam.setYearPart(enrollTeamParent.getYearPart());
                enrollTeam.setQuarterNum(enrollTeamParent.getQuarterNum());
            }
            if (enrollTeam.getStatus().equals(1)) {
                enrollTeam.setEndDate(LocalDate.parse("2099-12-31"));
            } else {
                enrollTeam.setEndDate(enrollTeam.getEndDate());
            }
            boolean rs = iEnrollTeamService.save(enrollTeam);
            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, "", e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id, @RequestBody EnrollTeam enrollTeam) {
        Organization organization = iOrganizationService.getById(enrollTeam.getSchoolId());
        if (organization != null) {
            enrollTeam.setSchoolName(organization.getName());
        }

        // 查询是否为大战队
        if (enrollTeam.getPid() == 0) {
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("pid", enrollTeam.getId());
            List<EnrollTeam> teamList = iEnrollTeamService.list(wrapper);

            for (EnrollTeam e : teamList) {
                EnrollTeam team = new EnrollTeam();
                team.setYearPart(enrollTeam.getYearPart());
                team.setQuarterNum(enrollTeam.getQuarterNum());
                team.setId(e.getId());
                iEnrollTeamService.updateById(team);
            }
            if (enrollTeam.getStatus().equals(0)) {
                String atTeamName = iEnrollTeamService.getChilTeamAtDataName(enrollTeam.getId(), enrollTeam.getStartDate().toString(), enrollTeam.getEndDate().toString());
                if (StringUtils.isNotBlank(atTeamName)) {
                    return new Result(Code.ERROR, "", "小战队：" + atTeamName + "，开始或结束时间再不在当前时间内，修改失败");
                }
            }
        } else {
            EnrollTeam enrollTeamParent = iEnrollTeamService.getById(enrollTeam.getPid());
            if (enrollTeamParent == null) {
                return new Result(Code.ERROR, "", "大战队不存在，修改失败");
            }
            if (enrollTeam.getStartDate().isBefore(enrollTeamParent.getStartDate())) {
                return new Result(Code.ERROR, "", "开始时间不能小于大战队的开始时间，修改失败");
            }
            if (enrollTeam.getStatus().equals(0) && enrollTeam.getEndDate() != null) {
                if (enrollTeam.getEndDate().isAfter(enrollTeamParent.getEndDate())) {
                    return new Result(Code.ERROR, "", "结束时间不能大于大战队的开始时间，修改失败");
                }

                EnrollInfo enrollInfo = iEnrollInfoService.getMinAndMaxDate(enrollTeam.getId(), enrollTeam.getStartDate().toString(), enrollTeam.getEndDate().toString());
                if (enrollInfo != null) {
                    String msg = "";
                    msg = enrollInfo.getMinAddDate() + "至" + enrollInfo.getMaxAddDate();
                    return new Result(Code.ERROR, "", "当前战队的存在招生信息最小与最大时间为：" + msg + "，修改失败");
                }
            }
        }
        if (enrollTeam.getStatus().equals(1)) {
            enrollTeam.setEndDate(LocalDate.parse("2099-12-31"));
        }
        boolean rs = iEnrollTeamService.updateById(enrollTeam);
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {
        try {
            EnrollTeam enrollTeam = iEnrollTeamService.getById(id);
            if (enrollTeam.getPid() != null && enrollTeam.getPid().equals(0L)) {
                QueryWrapper wrapper = new QueryWrapper<>();
                wrapper.eq("pid", enrollTeam.getId());
                Long count = iEnrollTeamService.count(wrapper);
                if (count > 0) {
                    return new Result(Code.ERROR, "", "存在小战队，不能删除");
                }

            }
            QueryWrapper<EnrollTeamMember> enrollTeamMemberQueryWrapper = new QueryWrapper<>();
            enrollTeamMemberQueryWrapper.eq("team_id", enrollTeam.getId());
            Long count = iEnrollTeamMemberService.count(enrollTeamMemberQueryWrapper);
            if (count > 0) {
                return new Result(Code.ERROR, "", "存在队员，不能删除");
            }

            boolean rs = iEnrollTeamService.removeById(id);

            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }

    @GetMapping("checkTeacher")
    public Result checkTeacher(@RequestParam Map reMap, @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 1000 : Integer.valueOf((String) reMap.get("pageSize"));

        IPage<Staff> page = new Page<>(pageNum, pageSize);

        String teamId = (String) reMap.get("teamId");

        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();

        String name = (String) reMap.get("name");
        if (StringUtils.isNotBlank(name)) {
            staffQueryWrapper.like("name", name);
        }

        if (schoolIdList.length > 0) {
            String schoolIdStr = String.join(",", schoolIdList);
            staffQueryWrapper.and(i -> i.eq("scope_class_mode", 1).or().inSql("id", "select for_id from appoint_school where type=2 and school_id in(" + schoolIdStr + ")"));
        } else {
            //System.out.print("baseSchoolIdStr:"+baseSchoolIdStr);
            staffQueryWrapper.and(i -> i.eq("scope_class_mode", 1).or().inSql("id", "select for_id from appoint_school where type=2 and school_id in(" + this.baseSchoolIdStr + ")"));
        }

        if (StringUtils.isNotBlank(teamId)) {
            staffQueryWrapper.notInSql("id", "select teacher_id from enroll_team_member where status = 1 and deleted=0");
        }
        //staffQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);

        iStaffService.findAll(page, staffQueryWrapper);

        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }

    /**
     * 添加战队成员
     *
     * @param enrollTeam
     * @return
     */
    @PostMapping("/addBatchMember")
    public Result addBatchMember(@RequestBody EnrollTeam enrollTeam) {
        iEnrollTeamService.addBatchMember(enrollTeam);
        return new Result(Code.OK, "", "");
    }

    /**
     * 批量移除队员
     *
     * @param enrollTeam
     * @return
     */
    @DeleteMapping("/removeBatchMember")
    public Result removeBatchMember(@RequestBody EnrollTeam enrollTeam) {
        boolean rs = iEnrollTeamService.removeBatchMember(enrollTeam);
        return new Result(rs ? Code.OK : Code.ERROR);
    }


    /**
     * 批量删除队员（添加错误需要删除）
     *
     * @param enrollTeam
     * @return
     */
    @DeleteMapping("/delBatchMember")
    public Result delBatchMember(@RequestBody EnrollTeam enrollTeam) {
        List<String> nameList = new ArrayList<>();
        for (Long id : enrollTeam.getTeacherIdList()) {
            EnrollTeamMember enrollTeamMemberInfo = iEnrollTeamMemberService.getById(id);
            QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
            enrollInfoQueryWrapper.eq("teacher_id", enrollTeamMemberInfo.getTeacherId());
            enrollInfoQueryWrapper.eq("team_id", enrollTeamMemberInfo.getTeamId());
            enrollInfoQueryWrapper.eq("is_return", 0);
            Long count = iEnrollInfoService.count(enrollInfoQueryWrapper);
            if (count > 0) {
                Staff staff = iStaffService.getById(enrollTeamMemberInfo.getTeacherId());
                nameList.add(staff.getName());
            }
        }
        if (nameList.size() > 0) {
            return new Result(Code.ERROR, "", String.join(",", nameList) + "在当前战队存在招生数据，不能删除");
        }

        boolean rs = iEnrollTeamService.delBatchMember(enrollTeam);
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    @PutMapping("/setTeamCaptain/{teamId}/{teacherId}")
    public Result setTeamCaptain(@PathVariable(value = "teamId") String teamId, @PathVariable(value = "teacherId") String teacherId) {
        //System.out.println(dict);
        boolean rs = iEnrollTeamService.setTeamCaptain(teamId, teacherId);
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    /**
     * 获取战队成员
     *
     * @param reMap
     * @return
     */
    @GetMapping("/getTeamMemberList")
    public Result getTeamMemberList(@RequestParam Map reMap) {
        try {
            String teamId = (String) reMap.get("teamId");
            String status = (String) reMap.get("status");
            String name = reMap.get("name") != null ? (String) reMap.get("name") : "";

            List<EnrollTeamMember> enrollTeamMemberList = iEnrollTeamService.getTeamMemberList(teamId, name, status);
            return new Result(Code.OK, enrollTeamMemberList);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }
}
